﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SFWS.XHandler.Core;
using JKF.Substructure;
using JKF.Entities.Model;
using JKF.BusinessLayer.BLL;
using System.Data;
using JKF.Entities;

namespace JKF.HandlerLayer.SMS
{
    public partial  class Call_LogHandler:AHttpHandler
    {
        private static bllCALL_LOG bllCall_log = new bllCALL_LOG();
        public override void ProcessRequest()
        {
            //所有错误和异常将抛出异常.正常执行程序则在方法则返回数据
            try
            {
                this.Manager(Utils.GetActionName);
            }
            catch (Exception ex)
            {
                //将错误抛到客户端(以Json格式)
                Utils.ToClient(true, ex.Message);
                //写日志
                AppLogger.Log(ex.Message, ex);
            }
        }

        /// <summary>
        /// 添加通话记录
        /// </summary>
        public void InsertCALL_LOG()
        {
            try
            {
                //DateTime dtime = DateTime.Parse("2013-02-28 14:16");
                var strScr = P("moduleObj"); 
                //第二个参数是用于指定日期转换格式
                var call_logModel = this.BuildCALL_LOGModel(JsonSerializer.Deserialize<CALL_LOGinfo>(strScr, "yyyy-MM-dd HH:mm"), false);
                 
                #region 作废，采用了记录操作日志方式
               /* if (call_logModel.CUSTOMER_KEY == new Guid())
                {//表明是新顾客
                    string sql = string.Format("insert into call_log( NAME, SEX, PHONE, CALL_DATE, CUSTOMER_KEY, CONTENT, SOUND_URL, MEMO, STATUS, SHOP_CODE, USER_CREATE, DATE_CREATE, DATE_UPDATE) values('{0}','{1}','{2}','{3}',NULL,'{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}')", call_logModel.NAME, call_logModel.SEX, call_logModel.PHONE, call_logModel.CALL_DATE.ToString(), call_logModel.CONTENT, call_logModel.SOUND_URL, call_logModel.MEMO, call_logModel.STATUS, call_logModel.SHOP_CODE, call_logModel.USER_CREATE, call_logModel.DATE_CREATE, call_logModel.DATE_UPDATE);
                    //如果顾客的key为空，则进行sql语句插入
                    if (!bllCall_log.TransationSql(sql))
                    {
                        throw new Exception("插入通话记录失败！");
                    }
                }
                else
                {
                    //表示是老顾客的通话记录登记
                    bllCall_log.Add(call_logModel);
                } */
                #endregion

                if (!bllCall_log.AddCallLogBLL(call_logModel))
                {
                    throw new Exception("添加通话记录失败！");
                }
                var pk = call_logModel.ID;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "添加成功.", Data = pk }));
            }
            catch (Exception exp)
            { 
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
        /// <summary>
        /// 编辑通话记录
        /// </summary>
        public void EditCALL_LOG()
        {
            try
            {
                var strScr = P("moduleObj");
                //第二个参数是用于指定日期转换格式
                var call_logModel = this.BuildCALL_LOGModel(JsonSerializer.Deserialize<CALL_LOGinfo>(strScr, "yyyy-MM-dd HH:mm"), true);
                //bllCall_log.Update(call_logModel);
                if (!bllCall_log.UpdateCallLogBLL(call_logModel))
                {
                    throw new Exception("修改通话记录失败！");
                }
                var pk = call_logModel.ID;
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Message = "修改成功.", Data = pk }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
       /// <summary>
        /// 根据前台传递的值来组装实体
       /// </summary>
       /// <param name="call_loginfo"></param>
       /// <param name="isEdit"></param>
       /// <returns></returns>
        private CALL_LOGinfo BuildCALL_LOGModel(CALL_LOGinfo call_loginfo, bool isEdit)
        {
            var entity = new CALL_LOGinfo();
            if (!isEdit) // 添加
            {
                entity.ID = new Guid(DB.GetNewGuid(DB.HR)); //Guid.NewGuid();
            }
            else // 修改
            {
                entity.ID = call_loginfo.ID;
            }
            entity.NAME = call_loginfo.NAME;
            entity.PHONE = call_loginfo.PHONE;
            entity.SHOP_CODE = bllSYS_USER.CurrentUser.SHOP_CODE; // 哪个店铺的通话记录
            entity.SEX = call_loginfo.SEX;
            entity.MEMO = call_loginfo.MEMO;
            entity.SOUND_URL = string.Empty;
            entity.STATUS = "1"; //1表示有效
            entity.CALL_DATE = call_loginfo.CALL_DATE;
            entity.CONTENT = call_loginfo.CONTENT; 
            entity.CUSTOMER_KEY = call_loginfo.CUSTOMER_KEY;//顾客的key, 
            entity.USER_CREATE = bllSYS_USER.CurrentUser.USER_KEY; // 获取当前用户guid
            entity.DATE_CREATE = System.DateTime.Now;
            entity.DATE_UPDATE = System.DateTime.Now;
            return entity;
        }
        /// <summary>
        /// 获取通话记录列表
        /// </summary>
        public void GetCALL_LOGS()
        {
            var obj = new PagerList();

            int pageCount = 0;
            int rowCount = 0;
            // NAME, ID, SEX, PHONE, CALL_DATE, CONTENT, MEMO, CARD_NO, LEVEL_NAME 
            obj.Entity = from a in bllCall_log.GetCALL_LOGSBLL(bllSYS_USER.CurrentUser, P("CARD_NO"), P("NAME"), P("PHONE"), P("LEVEL_NAME"), P("DATE_START"), P("DATE_END"), P("CUSTOMER_KEY"), P("ownShop"), P("PageIndex").ToInt32(), P("PageSize").ToInt32(), ref pageCount, ref rowCount).AsEnumerable()
                         select new
                         {
                             ID = a.Field<Guid>("ID"),
                             NAME = a.Field<string>("NAME"),
                             SEX = a.Field<string>("SEX"), 
                             PHONE = a.Field<string>("PHONE"),
                             CONTENT = a.Field<string>("CONTENT"),
                             MEMO = a.Field<string>("MEMO"), // 可能为空
                             CARD_NO = a.Field<string>("CARD_NO"),
                             LEVEL_NAME = a.Field<string>("LEVEL_NAME"),
                             CALL_DATE = (a.Field<DateTime>("CALL_DATE")).ToString("yyyy-MM-dd HH:mm")
                         };

            obj.RowCount = rowCount;
            obj.PageCount = pageCount;
            ResponseJsonObject = obj;
        }
        /// <summary>
        /// 删除通话记录，采用逻辑删除
        /// </summary>
        public void DeleteCALL_LOG()
        {
            try
            {
                var call_log_key = P("id");
                //string call_log_delete_sql = string.Format("update dbo.CALL_LOG set STATUS=9,DATE_UPDATE=getdate()  where ID=@ID");
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Ok", Success = bllCall_log.DeleteCallLogBLL(call_log_key), Data = call_log_key }));

            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }

        /// <summary>
        /// 根据主键获取顾客通话记录
        /// </summary>
        public void GetCALL_LOGByCode()
        {
            try
            {
                var scid = P("moduleKey");
                var call_log_model = bllCall_log.GetModel(new Guid(scid));
                CUSTOMERinfo customer_model =null;
                if (call_log_model.CUSTOMER_KEY != new Guid())
                {
                    customer_model = new bllCUSTOMER().GetModel(call_log_model.CUSTOMER_KEY);
                }
                Response.Write(JsonSerializer.Serialize(
                    new ResponseInf
                    {
                        MessageCode = "Ok",
                        Data = call_log_model,
                         Mode= customer_model,
                        FormatString = call_log_model.CALL_DATE.ToString("yyyy-MM-dd HH:mm")
                    }));
            }
            catch (Exception exp)
            {
                Response.Write(JsonSerializer.Serialize(new ResponseInf { MessageCode = "Error", Message = exp.Message.FilterJs() }));
            }
        }
    }
}
